/**
 *    Copyright 2006-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.mybatis.generator.plugins;

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.ArrayList;
import java.util.List;

/**
 * 生成dto
 */
public class AdditionalDTOGeneratorPlugin extends PluginAdapter {

    // 项目目录，一般为 src/main/java
    private String targetProject;//config

    // dto包名，如：com.a.b
    private String dtoPackage;//config

    // dto接口名后缀 如 DTO/BO 
    private String dtoSuffix;//config

    // service接口的父接口
    private String superDTOInterface;

    private String importTypes;//自定义引入的类//config

    private static final String import_split = ";";//引入类的分隔符

    private boolean isNeeded = false;//是否需要生成dto//config

    private TopLevelClass modelClazzDTO;//

    @Override
    public boolean validate(List<String> warnings) {
        targetProject = properties.getProperty("targetProject");
        importTypes = properties.getProperty("importTypes");
        dtoPackage = properties.getProperty("dtoPackage");
        dtoSuffix = properties.getProperty("dtoSuffix");
        isNeeded = properties.getProperty("isNeeded").equalsIgnoreCase("true") ? true : false;
        return true;
    }


    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        //add file
        List<GeneratedJavaFile> answer = new ArrayList<GeneratedJavaFile>();
        if (modelClazzDTO != null) {
            if (!StringUtility.stringHasValue(targetProject)) {
                //use model type as default if target package not configured
                targetProject = introspectedTable.getContext().getJavaModelGeneratorConfiguration().getTargetProject();
            }
            GeneratedJavaFile controllerJavaFile = new GeneratedJavaFile(modelClazzDTO, targetProject, context.getJavaFormatter());
            answer.add(controllerJavaFile);
            return answer;
        }
        return null;
    }

    /**
     * 生成dto class
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        if (isNeeded) {
            //需要生成dto
            FullyQualifiedJavaType type = topLevelClass.getType();
            FullyQualifiedJavaType newType = null;
            if (StringUtility.stringHasValue(dtoPackage)) {
                //配置中提供了 dto的package
                String shortName = type.getShortName();
                newType = new FullyQualifiedJavaType(String.format("%s.%s%s", dtoPackage, shortName, dtoSuffix));
            } else {
                //未提供dto package 则生成到 model的同一级目录
                newType = new FullyQualifiedJavaType(type.getFullyQualifiedNameWithoutTypeParameters() + dtoSuffix);
            }
            modelClazzDTO = new TopLevelClass(newType);
            modelClazzDTO.setVisibility(JavaVisibility.PUBLIC);
            for (FullyQualifiedJavaType fullyQualifiedJavaType : topLevelClass.getImportedTypes()) {
                modelClazzDTO.addImportedType(fullyQualifiedJavaType);
            }
            for (Method method : topLevelClass.getMethods()) {
                modelClazzDTO.addMethod(method);
            }
            for (Field field : topLevelClass.getFields()) {
                modelClazzDTO.addField(field);
            }
            //********************************
            //*import some java types
            //*********************************
            
            //common import
            modelClazzDTO.addImportedType(new FullyQualifiedJavaType("com.fasterxml.jackson.annotation.JsonIgnoreProperties"));
            if (StringUtility.stringHasValue(importTypes)) {
                String[] split = importTypes.split(import_split);
                for (String imprt : split) {
                    modelClazzDTO.addImportedType(new FullyQualifiedJavaType(imprt));
                }
            } else {
                //need change
//                modelClazzDTO.addImportedType(new FullyQualifiedJavaType("org.mybatis.generator.plugins.custome.PageQuery"));
            }
            //extends  page query 
//            modelClazzDTO.setSuperClass(new FullyQualifiedJavaType("PageQuery"));
            modelClazzDTO.addAnnotation("@JsonIgnoreProperties(ignoreUnknown = true)");
        }
        return true;
    }
}